#include "article_redis_adapter.h"

#include <map>
#include <thrift/Thrift.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>

#include "base/logging.h"
// #include "redis_executor/scoped_reply.h"

using namespace std;
using namespace boost;
using namespace base;
using namespace apache::thrift;

namespace jztzp {

int ArticleRedisAdapter::SetContent(int32_t article_id, const string & content) {
  const int MAX_BUF_LEN = 64;
  char cmd_buf[MAX_BUF_LEN];
  cmd_buf[MAX_BUF_LEN - 1] = '\0';

  snprintf(cmd_buf, MAX_BUF_LEN - 1, "SET article:body:%d %%b", article_id);
  ScopedReply reply(redis_exec.Execute("", cmd_buf, content.c_str(), content.size()));
  // Status code reply: always OK since SET can't fail.
  if (!reply) {
    LOG_ERROR("set article error, id=" << article_id);
    return -1;
  }
  LOG_INFO("set article body ok, id=" << article_id);

  return 0;
}

int ArticleRedisAdapter::RemoveContent(int32_t article_id) {
  const int MAX_BUF_LEN = 64;
  char cmd_buf[MAX_BUF_LEN];
  cmd_buf[MAX_BUF_LEN - 1] = '\0';

  {
    snprintf(cmd_buf, MAX_BUF_LEN - 1, "DEL article:body:%d", article_id);
    // Integer reply: The number of keys that were removed.
    ScopedReply reply(redis_exec.Execute("", cmd_buf));
    if (reply) {
      if (reply->type == REDIS_REPLY_INTEGER) {
         LOG_DEBUG(cmd_buf << " success, reply=" << reply->integer);
      } else {
         LOG_WARN(cmd_buf << " bad reply type, type=" << reply->type);
         return -1;
      }
    } else {
      LOG_WARN(cmd_buf << ", null reply, may be connection err.");
      return -1;
    }
  }

  return 0;
}

int ArticleRedisAdapter::GetContent(int32_t article_id, string * content) {
  const int MAX_BUF_LEN = 64;
  char cmd_buf[MAX_BUF_LEN];
  cmd_buf[MAX_BUF_LEN - 1] = '\0';

  {
    snprintf(cmd_buf, MAX_BUF_LEN - 1, "GET article:body:%d", article_id);
    // Bulk reply: the value of key, or nil when key does not exist.
    ScopedReply reply(redis_exec.Execute("", cmd_buf));
    if (reply) {
      if (reply->type == REDIS_REPLY_STRING) {
         content->assign(reply->str, reply->len);
         LOG_INFO(cmd_buf << " success, size=" << reply->len);
      } else {
         LOG_INFO(cmd_buf << " return NIL");
         return -1;
      }
    } else {
      LOG_WARN(cmd_buf << ", null reply, may be connection err.");
      return -1;
    }
  }

  return 0;
}

}

